
// 143.重排链表
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    void reorderList(ListNode* head) {
        // 相减后半部分链表进行反转
        // 先通过快慢指针找中间位置
        ListNode* slow = head , *fast = head;
        while(fast && fast->next)
        {
            slow = slow->next;
            fast = fast->next->next;
        }
        // 此时slow是中间位置, 从中间位置进行反转
        auto back_reverse = [](ListNode* start)
        {
            ListNode* prev = nullptr , *cur = start;
            while(cur)
            {
                ListNode* next = cur->next;
                cur->next = prev;
                prev = cur;
                cur = next;
            }
            return prev;
        };

        ListNode* back = back_reverse(slow) , *cur = head;
        while(cur!= back && cur -> next != back)
        {
            ListNode* back_next = back->next , *cur_next = cur->next;
            cur->next = back;
            back->next = cur_next;
            cur = cur_next , back = back_next;
        }
    }
};